package com.example.demo.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class AppProviderCallBack implements MqttCallback {
    private MqttClient client;
    private MqttConnectOptions options;

    public AppProviderCallBack(MqttClient client, MqttConnectOptions options) {
        this.client = client;
        this.options = options;
    }

    /**
     * 连接丢失时被调用
     *
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        log.info("AppProviderCallBack connection lost：" + cause.getMessage());
        log.info(client.getClientId() + "与服务器断开连接");

        if (client != null) {
            if (!client.isConnected()) {
                try {
                    log.info("重新尝试连接");
                    client.reconnect();
                } catch (MqttException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            log.info("mqtt连接异常,连接为空");
            throw new RuntimeException("连接为空");
        }

    }

    /**
     * 接收到消息是被调用(订阅的时候使用)
     *
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("Received message: \n  topic：" + topic + "\n  Qos：" + message.getQos() + "\n  payload：" + new String(message.getPayload()));
        // 处理消息
        String msg = new String(message.getPayload());
        System.out.println("接收到MQTT消息：=================>>>" + msg);
    }

    /**
     * 客户端发送消息到服务端时被调用(发布的时候使用)
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {


//        IMqttAsyncClient client = iMqttDeliveryToken.getClient();
//        try {
//            //通过接收到的消息修改数据的状态
//            String message = new String(iMqttDeliveryToken.getResponse().getPayload());
//            log.info(message);
//        } catch (MqttException e) {
//            throw new RuntimeException(e);
//        }
    }
}